package service

import (
	"github.com/gin-gonic/gin"
	"zk2/product-guard/internal/dto"
	"zk2/product-guard/internal/model"
	"zk2/product-guard/pkg"
	"zk2/product-guard/response"
)

func Login(c *gin.Context) {

	var user model.User
	err := c.ShouldBind(&user)
	if err != nil {
		response.Error(c, "参数错误")
		return
	}
	dto.Find(&user, user.Username)
	if user.ID == 0 {
		user = model.User{
			Username: user.Username,
			Password: user.Password,
		}
		err = dto.Login(&user)
		if err != nil {
			response.Error(c, "注册失败")
			return
		} else {
			response.Success(c, "注册成功", user.ID)
			return
		}
	}
	var NewUser model.User
	err = c.ShouldBind(&NewUser)
	if err != nil {
		response.Error(c, "参数错误")
		return
	}
	if NewUser.Password != user.Password {
		response.Error(c, "密码错误")
		return
	}
	handler, err := pkg.TokenHandler(int(user.ID))
	if err != nil {
		response.Error(c, "生成失败")
		return
	}
	response.Success(c, "登录成功", handler)
}
